﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NSISBg
{
    /// <summary>
    /// Success.xaml 的交互逻辑
    /// </summary>
    public partial class Success : Window
    {
        public Success()
        {
            InitializeComponent();
            this.Loaded += Success_Loaded;
        }

        void Success_Loaded(object sender, RoutedEventArgs e)
        {
            var bitmapSource = RenderVisaulToBitmap(this, (int)this.ActualWidth, (int)this.ActualHeight);
            using (var fileStream = new FileStream("success.bmp", FileMode.Create))
            {
                GenerateImage(bitmapSource, NSISBg.Button.ImageFormat.BMP, fileStream);
            }
        }

        private void Window_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        private RenderTargetBitmap RenderVisaulToBitmap(Visual vsual, int width, int height)
        {
            var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
            rtb.Render(vsual);

            return rtb;
        }

        private void GenerateImage(BitmapSource bitmap, NSISBg.Button.ImageFormat format, Stream destStream)
        {
            BitmapEncoder encoder = null;

            switch (format)
            {
                case NSISBg.Button.ImageFormat.JPG:
                    encoder = new JpegBitmapEncoder();
                    break;
                case NSISBg.Button.ImageFormat.PNG:
                    encoder = new PngBitmapEncoder();
                    break;
                case NSISBg.Button.ImageFormat.BMP:
                    encoder = new BmpBitmapEncoder();
                    break;
                case NSISBg.Button.ImageFormat.GIF:
                    encoder = new GifBitmapEncoder();
                    break;
                case NSISBg.Button.ImageFormat.TIF:
                    encoder = new TiffBitmapEncoder();
                    break;
                default:
                    throw new InvalidOperationException();
            }

            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(destStream);
        }
    }
}
